package com.martin.dms.web.services.impl;

import java.util.ArrayList;
import java.util.List;

import com.martin.dms.model.Category;
import com.martin.dms.model.Item;
import com.martin.dms.services.CategoryService;
import com.martin.dms.services.ItemService;
import com.martin.dms.web.beans.CategoryBean;
import com.martin.dms.web.beans.ItemBean;
import com.martin.dms.web.beans.ItemManagementBean;
import com.martin.dms.web.services.ItemFlowService;

/**
 * Implementation of the ItemFlowService.
 * 
 * @author mtsvetkov
 */
public class ItemFlowServiceImpl implements ItemFlowService {

    private ItemService itemService;

    private CategoryService categoryService;

    /**
     * Constructor.
     * 
     * @param itemService - service for item management.
     * @param categoryService - service for category management.
     */
    public ItemFlowServiceImpl(ItemService itemService, CategoryService categoryService) {
        this.itemService = itemService;
        this.categoryService = categoryService;
    }

    /**
     * {@inheritDoc}
     */
    public List<CategoryBean> getAllCategories() {
        List<CategoryBean> result = new ArrayList<CategoryBean>();
        List<Category> categories = categoryService.getAll();
        for (Category category : categories) {
            result.add(new CategoryBean(category, false));
        }
        return result;
    }

    /**
     * {@inheritDoc}
     */
    public List<ItemBean> searchItems(ItemManagementBean bean, boolean searchForItems) {
        List<ItemBean> result = new ArrayList<ItemBean>();
        if (searchForItems) {
            List<Item> items = itemService.findByNameAndCategory(bean.getItemNameFilter(), bean.getCategoryId());
            for (Item item : items) {
                result.add(new ItemBean(item.getId(), item.getName()));
            }
        }
        return result;
    }

    /**
     * {@inheritDoc}
     */
    public ItemBean getItem(long id, boolean copyAllData) {
        Item item = itemService.get(id);
        if (copyAllData) {
            return new ItemBean(item);
        } else {
            return new ItemBean(item.getId(), item.getName());
        }
    }

    /**
     * {@inheritDoc}
     */
    public void deleteItem(ItemBean item) {
        itemService.delete(item.getId());
    }

    /**
     * {@inheritDoc}
     */
    public void saveItem(ItemBean item) {
        if (item.getId() != null) {
            itemService.update(item.getId(), item.getName(), item.getCategoryId(), item.getIntPrice(), item
                    .getDescription(), item.getImageBytes());
        } else {
            itemService.create(item.getName(), item.getCategoryId(), item.getIntPrice(), item.getDescription(), item
                    .getImageBytes());
        }
    }

}
